package org.sky.component.fileupload;

import java.io.File;
import java.io.InputStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.baidu.inf.iis.bcs.BaiduBCS;
import com.baidu.inf.iis.bcs.auth.BCSCredentials;
import com.baidu.inf.iis.bcs.model.ObjectMetadata;
import com.baidu.inf.iis.bcs.model.X_BS_ACL;
import com.baidu.inf.iis.bcs.request.PutObjectRequest;
import com.baidu.inf.iis.bcs.response.BaiduBCSResponse;

/**百度云服务
 * @author ws
 *
 */
public class BaeFileUpload {
	private static final Log log = LogFactory.getLog(BaeFileUpload.class);
	// ----------------------------------------
	static String host = "bcs.duapp.com";
	static String accessKey = "qatLdmosgLorDoQZu6LOskIx";
	static String secretKey = "VcaLOUlidrvtdfgR3ltuTx8x1fHOQFi6";
	static String bucket = "wssaidong";
	static String object = "/first-object";
	//-----------------------------------------
	public static void upload(File file,String fileName){
		object=fileName;
		BCSCredentials credentials = new BCSCredentials(accessKey, secretKey);
		BaiduBCS baiduBCS = new BaiduBCS(credentials, host);
		baiduBCS.setDefaultEncoding("UTF-8"); 
		putObjectByFile(baiduBCS,file);
	}
	
	private static void putObjectByFile(BaiduBCS baiduBCS,File file) {
		PutObjectRequest request = new PutObjectRequest(bucket, object, file);
		ObjectMetadata metadata = new ObjectMetadata();
		request.setMetadata(metadata);
		request.setAcl(X_BS_ACL.PublicRead) ;
		BaiduBCSResponse<ObjectMetadata> response = baiduBCS.putObject(request);
		ObjectMetadata objectMetadata = response.getResult();
		log.info("x-bs-request-id: " + response.getRequestId());
		log.info(objectMetadata);
	}
	//
	public static void upload(InputStream inputStream,String fileName,Long size){
		object=fileName;
		BCSCredentials credentials = new BCSCredentials(accessKey, secretKey);
		BaiduBCS baiduBCS = new BaiduBCS(credentials, host);
		baiduBCS.setDefaultEncoding("UTF-8"); 
		putObjectByFile(baiduBCS,inputStream,size);
	}
	
	private static void putObjectByFile(BaiduBCS baiduBCS,InputStream inputStream,long size) {
		ObjectMetadata metadata = new ObjectMetadata();
		metadata.setContentType("text/html");
		metadata.setContentLength(size);
		PutObjectRequest request = new PutObjectRequest(bucket, object, inputStream,metadata);
		request.setMetadata(metadata);
		request.setAcl(X_BS_ACL.PublicRead) ;
		BaiduBCSResponse<ObjectMetadata> response = baiduBCS.putObject(request);
		ObjectMetadata objectMetadata = response.getResult();
		log.info("x-bs-request-id: " + response.getRequestId());
		log.info(objectMetadata);
	}
	private static File createSampleFile() {
					File file = new File("C:\\Users\\ws\\Desktop\\1.txt");
					return file;
	}
	public static void main(String[] args) {
		BaeFileUpload.upload(createSampleFile(),"/test.txt");
	}
}


